package com.example.administrator.robot_shanlong_app.socket;

import android.os.Handler;
import android.util.Log;

import com.example.administrator.robot_shanlong_app.constant.Flag;
import com.example.administrator.robot_shanlong_app.dataconvert.ConvertData;
import com.example.administrator.robot_shanlong_app.dataconvert.DeviceUtils;

import java.io.InputStream;
import java.net.Socket;
import java.io.OutputStream;
public class Receive_forServerMessage extends Thread {

    private static String TAG = Receive_forServerMessage.class.getSimpleName();
    //文件件流操作
    private InputStream input;
    private OutputStream output;
    //网络对象
    private Socket socket;
    private Handler hcilent;

    //数据更新SO
    public Receive_forServerMessage(Handler handler, Socket socket) {
        this.socket = socket;
        this.hcilent = handler;

    }

    @Override
    public void run() {
        try {

            while (true) {
                if (socket != null) {
                    input = socket.getInputStream();
                    output=socket.getOutputStream();
                    while (input.available() == 0) ;
                    Thread.sleep(2000);
                    final byte[] data = new byte[1024];
                    final int len = input.read(data);
                    //加判断如果为十六进制则以十六进制显示
                    if(DeviceUtils.IsHexString(data.toString())) {
                        hcilent.sendMessage(hcilent.obtainMessage(Flag.READ_STATE, len, -1, ConvertData.hexStr2Bytes(data.toString())));
                    }
                    else
                    {
                        hcilent.sendMessage(hcilent.obtainMessage(Flag.READ_STATE, len, -1, data));
                    }
                    if(output!=null)
                    {
                        output.write("ACK".getBytes());
                        output.flush();
                    }
                }
            }
        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
            hcilent.sendMessage(hcilent.obtainMessage(Flag.ERROR_STATE));
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
                if (input != null) {
                    input.close();
                }

            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }

    }
}
